package com.lufan.factory;


import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class HttpClientFactory {
    private static volatile OkHttpClient httpClient;
    private HttpClientFactory() {
    }
    public synchronized static OkHttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (HttpClientFactory.class) {
                if (httpClient == null) {
                    CookieJar cookieJar = new CookieJar() {
                        private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
                        @Override
                        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                            cookieStore.put(url.host(), cookies);
                        }
                        @NotNull
                        @Override
                        public List<Cookie> loadForRequest(HttpUrl url) {
                            List<Cookie> cookies = cookieStore.get(url.host());
                            return cookies != null ? cookies : new ArrayList<>();
                        }
                    };
                     httpClient = new OkHttpClient.Builder()
                            .connectTimeout(10, TimeUnit.SECONDS)
                             .cookieJar(cookieJar)
                            .build();
                }
            }
        }
        return httpClient;
    }

}
